//
//  LFLoadSiteController.m
//  LoveFruit
//
//  Created by 张令林 on 16/9/27.
//  Copyright © 2016年 张令林. All rights reserved.
//

#import "LFLoadSiteController.h"
#import <CoreLocation/CoreLocation.h>

@interface LFLoadSiteController ()<CLLocationManagerDelegate>

@property (nonatomic, strong) CLLocationManager* locationManager;


@end

@implementation LFLoadSiteController

- (instancetype)init
{
    self = [super init];
    if (self) {
        [self setUpUI];
        self.isFirstTime = YES;
    }
    return self;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    [self setUpUI];
}

- (void)setUpUI
{
    //检测定位功能是否开启
    if([CLLocationManager locationServicesEnabled])
    {
        if(!_locationManager)
        {
            self.locationManager = [[CLLocationManager alloc] init];
            if([self.locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)])
            {
                
                [self.locationManager requestWhenInUseAuthorization];
                [self.locationManager requestAlwaysAuthorization];
            }
            //设置代理
            [self.locationManager setDelegate:self];
            //设置定位精度
            [self.locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
            //设置距离筛选
            [self.locationManager setDistanceFilter:100];
            //开始定位
            [self.locationManager startUpdatingLocation];
            //设置开始识别方向
            [self.locationManager startUpdatingHeading];
        }
    }else
    {
        self.isOpenSiteLoad = @"没有开启定位";
        self.loadcity = nil;
    }
}
#pragma mark - CLLocationManangerDelegate
//定位成功以后调用
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
    
    [self.locationManager stopUpdatingLocation];
    CLLocation* location = locations.lastObject;
    [self reverseGeocoder:location];
}

#pragma mark Geocoder
//反地理编码
- (void)reverseGeocoder:(CLLocation *)currentLocation
{
    
    CLGeocoder* geocoder = [[CLGeocoder alloc] init];
    [geocoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray *placemarks, NSError *error) {
        if(error || placemarks.count == 0)
        {
            NSLog(@"error = %@",error);
        }else
        {
            CLPlacemark* placemark = placemarks.firstObject;
            NSLog(@"placemark:%@",[[placemark addressDictionary] objectForKey:@"City"]);
            self.loadcity = [[placemark addressDictionary] objectForKey:@"City"];
            self.showCity();
        }
    }];
}


@end
